import { defineStore } from 'pinia';
import axios from '../utils/axios';

export const useCategoryStore = defineStore('category', {
  state: () => ({
    categories: [],
    currentCategory: null,
    loading: false,
    error: null
  }),

  getters: {
    allCategories: (state) => state.categories,
    categoryById: (state) => (id) => state.categories.find(category => category.id === id)
  },

  actions: {
    async fetchCategories() {
      this.loading = true;
      try {
        const response = await axios.get('/categories');
        this.categories = response;
        this.error = null;
      } catch (error) {
        console.error('Failed to fetch categories:', error);
        this.error = 'Failed to fetch categories';
      } finally {
        this.loading = false;
      }
    },

    async fetchCategoryById(id) {
      this.loading = true;
      try {
        const response = await axios.get(`/categories/${id}`);
        this.currentCategory = response;
        this.error = null;
        return response;
      } catch (error) {
        console.error('Failed to fetch category:', error);
        this.error = 'Failed to fetch category';
      } finally {
        this.loading = false;
      }
    },

    async createCategory(categoryData) {
      try {
        const response = await axios.post('/categories', categoryData);
        this.categories.push(response);
        return response;
      } catch (error) {
        console.error('Failed to create category:', error);
        this.error = 'Failed to create category';
        throw error;
      }
    },

    async updateCategory(id, categoryData) {
      try {
        const response = await axios.put(`/categories/${id}`, categoryData);
        const index = this.categories.findIndex(category => category.id === id);
        if (index !== -1) {
          this.categories[index] = response;
        }
        if (this.currentCategory && this.currentCategory.id === id) {
          this.currentCategory = response;
        }
        return response;
      } catch (error) {
        console.error('Failed to update category:', error);
        this.error = 'Failed to update category';
        throw error;
      }
    },

    async deleteCategory(id) {
      try {
        await axios.delete(`/categories/${id}`);
        this.categories = this.categories.filter(category => category.id !== id);
        if (this.currentCategory && this.currentCategory.id === id) {
          this.currentCategory = null;
        }
      } catch (error) {
        console.error('Failed to delete category:', error);
        this.error = 'Failed to delete category';
        throw error;
      }
    }
  }
});